package com.lagou.dao;

import com.lagou.domain.Student;
import com.lagou.util.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;

public class StudentDAO {

    // 创建QueryRunner对象
    private static QueryRunner qr = GenericDAO.getRunner();

    // 定义查询方法 - 判断指定学号的学生是否存在
    public static int find(int stdNo) throws SQLException {

        String sql = "SELECT COUNT(*) FROM student WHERE stdNo = ?";
        long query = qr.query(sql, new ScalarHandler<>(), stdNo);
        return (int) query;
    }

    // 定义插入学生的方法
    public static int insert(Student std) throws SQLException {

        // 插入数据之前先查询下是否有学号相同的数据
        int i = find(std.getStdNo());
        if (i > 0) return -1;

        String sql = "INSERT INTO Student VALUES (?, ?, ?, ?)";

        int cnt = qr.update(sql, std.getStdNo(), std.getStdName(), std.getStdGender(), std.getBirthDate());

        return cnt;

    }
}
